package onlyJava;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class JpegCompressor {

    /**
     * 压缩 JPG 图片
     *
     * @param inputPath  输入图片路径
     * @param outputPath 输出图片路径
     * @param quality    压缩质量 (0.0 ~ 1.0)，建议 0.3~0.8
     */
    public static void compressJpeg(String inputPath, String outputPath, float quality) throws IOException {
        // 读取图片
        BufferedImage image = ImageIO.read(new File(inputPath));

        // 获取 JPEG 写入器
        ImageWriter jpgWriter = ImageIO.getImageWritersByFormatName("jpg").next();
        ImageWriteParam jpgWriteParam = jpgWriter.getDefaultWriteParam();

        // 开启压缩模式
        jpgWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        jpgWriteParam.setCompressionQuality(quality); // 质量 0~1

        // 输出流
        try (FileOutputStream fos = new FileOutputStream(outputPath);
             ImageOutputStream ios = ImageIO.createImageOutputStream(fos)) {
            jpgWriter.setOutput(ios);
            jpgWriter.write(null, new IIOImage(image, null, null), jpgWriteParam);
        }

        jpgWriter.dispose();
    }

    public static void main(String[] args) throws IOException {
        compressJpeg("C:\\Users\\lenovo\\Desktop\\123\\44.jpg", "C:\\Users\\lenovo\\Desktop\\123\\446.jpg", 0.1f);
        System.out.println("压缩完成！");
    }
}
